import 'dart:io';

import 'package:dio/dio.dart';

import '../exception/http_exceptions.dart';


class HttpExceptionHelper {
 static HttpException parseException(Exception error) {
    if (error is DioError) {
      switch (error.type) {
        case DioExceptionType.connectionTimeout:
        case DioExceptionType.receiveTimeout:
        case DioExceptionType.sendTimeout:
          return NetworkException(message: error.message);
        case DioExceptionType.cancel:
          return CancelException(error.message);
        case DioExceptionType.badResponse:
          try {
            int? errCode = error.response?.statusCode;
            switch (errCode) {
              case 302:
                return UnauthorisedException(message: "登录过期",code: errCode);
              case 400:
                return BadRequestException(message: "请求语法错误", code: errCode);
              case 401:
                return UnauthorisedException(message: "没有权限", code: errCode);
              case 403:
                return BadRequestException(message: "服务器拒绝执行", code: errCode);
              case 404:
                return BadRequestException(message: "无法连接服务器", code: errCode);
              case 405:
                return BadRequestException(message: "请求方法被禁止", code: errCode);
              case 500:
                return BadServiceException(message: "服务器内部错误", code: errCode);
              case 502:
                return BadServiceException(message: "无效的请求", code: errCode);
              case 503:
                return BadServiceException(message: "服务器挂了", code: errCode);

              case 505:
                return UnauthorisedException(
                    message: "不支持HTTP协议请求", code: errCode);
              default:
                return UnknownException(error.message);
            }
          } on Exception catch (_) {
            return UnknownException(error.message);
          }

        case DioExceptionType.unknown:
          if (error.error is SocketException) {
            return NetworkException(message: error.message);
          } else {
            return UnknownException(error.message);
          }
        default:
          return UnknownException(error.message);
      }
    } else {
      return UnknownException(error.toString());
    }
  }
}